<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/8/6
 * Time: 14:02
 */
namespace app\api\controller;

use think\Db;
use app\api\model\ClassroomOrder as ClassroomOrderModel;//订单
use app\api\model\ActivityOrder as ActivityOrderModel;//捐赠
use app\api\model\Feedback as FeedbackModel;//意见反馈
use app\api\model\AboutUs as AboutUsModel;
use think\Exception;//关于我们

class My extends Common
{
    /**
     * Token验证
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return string|\think\response\Json
     */
    public function _initialize()
    {
        parent::_initialize (); // TODO: Change the autogenerated stub
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            echo json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"],256);
            exit;
        }
    }

    /**
     * 用户信息
     */
    public function getUserData(){
        extract(input());
        $data = Db::table('up_u_user u')
            ->join('up_area a','a.district_id = u.user_shi','left')
            ->where('user_id',$user_id)
            ->field('u.user_attestation,u.user_username,u.user_image,u.user_age,a.district,u.user_me_content,u.user_attestation')
            ->find();
        $this->apiSuccess ($data);
    }

    /**
     * 用户认证信息回显
     */
    public function getUserList(){
        extract(input());
        $data = Db::table('up_u_user u')
            ->join('up_area a','a.district_id = u.user_shi','left')
            ->join('up_assortment ua1','ua1.assortment_id = u.user_hospital','left')
            ->join('up_assortment ua2','ua2.assortment_id = u.user_department','left')
            ->join('up_assortment ua3','ua3.assortment_id = u.user_title','left')
            ->join('up_assortment ua4','ua4.assortment_id = u.user_post','left')
            ->join('up_mechanism um','um.mechanism_id = u.user_to_mechanism_id','left')
            ->where('user_id',$user_id)
            ->field('u.user_attestation,u.user_username,
            u.user_image,u.user_age,a.district,a.district_id,
            u.user_me_content,u.user_attestation,u.user_card,u.user_rel_name,
            ua1.assortment_name as hospital,ua2.assortment_name as department,
            ua3.assortment_name as title,ua4.assortment_name as post,u.user_business_image,
            um.mechanism_id,um.mechanism_name,u.user_hospital,u.user_department,u.user_title,u.user_post')
            ->find();
        $this->apiSuccess ($data);
    }
    /**
     * 修改用户信息
     * @throws \think\Exception
     */
    public function editUser(){
        extract(input());
        $param = [];
        if(isset($name)){
            $param['user_username'] = $name;
        }
        if(isset($image)){
            $param['user_image'] = $image;
        }
        if(isset($age)){
            $param['user_age'] = $age;
        }
        if(isset($district_id)){
            $param['user_shi'] = $district_id;
        }
        if(isset($content)){
            $param['user_me_content'] = $content;
        }
        $param['user_update_time'] = date('Y-m-d H:i:s');
        $res = Db::table('up_u_user')->where('user_id',$user_id)->update($param);
        if($res){
            $this->apiSuccess ();
        }else{
            $this->apiError (100,'修改失败');
        }
    }

    /**
     * 我的收藏
     */
    public function myCollect(){
        extract(input());
        if($type == 1){//收藏资讯
            $data = Db::table('up_my_collection')->alias('umc')
                ->join('up_information i', 'i.information_id = umc.information_id', 'left')
                ->join('up_mechanism m','i.mechanism_id = m.mechanism_id','left')
                ->where('umc.user_id',$user_id)
                ->field('i.information_id,i.information_title,i.information_content,
                i.information_img,i.information_introduce,i.information_release_time,
                m.mechanism_id,m.mechanism_name, umc.collection_id as collect_id')
                ->page($page,10)
                ->select();
//            $coll = Db::table('up_my_collection')
//                ->where('user_id',$user_id)
//                ->column('information_id');
//            $data = Db::table('up_information i')
//                ->join('up_mechanism m','i.mechanism_id = m.mechanism_id','left')
//                ->where('information_id','in',$coll)
//                ->field('i.information_id,i.information_title,i.information_content,i.information_img,i.information_introduce,i.information_release_time,m.mechanism_id,m.mechanism_name')
//                ->page($page,10)
//                ->select();
        }elseif($type == 2){//收藏的活动
            $data = Db::table('up_my_activities')->alias('uma')
                ->join('up_institutional_activities ia', 'ia.id = uma.institutional_activities_id', 'left')
                ->where('uma.user_id', $user_id)
                ->where('ia.is_show', 1)
                ->field('ia.id,ia.activity_name,ia.activity_address,ia.activity_img, uma.id as collect_id, 
                 ia.activity_start_time,ia.activity_end_time,ia.activity_status,ia.activity_id')
                ->page($page,10)
                ->select();
            foreach($data as $k=>&$v){
                $activity_name =Db::table('up_activity')->where('id','IN',trim($v['activity_id'],','))->column('activity_name');
                $v['activity_type_name'] = implode(',',$activity_name);
                
                $time_Y = date('Y');//当前的年
                $time_m = date('m');//当前的月
                $time_d = date('d');//当前的日
                $start_time = strtotime($v['activity_start_time']);
                $start_Y = date('Y', $start_time);//活动开始的年
                $start_m = date('m', $start_time);//活动开始的月
                $start_d = date('d', $start_time);//活动开始的日
                $start_Hi = date('H:i', $start_time);//活动开始的时分
                $end_time = strtotime($v['activity_end_time']);
                $end_Y = date('Y', $end_time);//活动结束的年
                $end_m = date('m', $end_time);//活动结束的月
                $end_d= date('d', $end_time);//活动结束的日
                $end_Hi = date('H:i', $end_time);//活动结束的时分
                if($time_Y == $start_Y && $time_Y == $end_Y){//今年
                    if($start_m == $end_m && $start_d == $end_d){//不跨天
                        $v['activity_start_time'] = $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_Hi;
                    }else{//跨天
                        $v['activity_start_time'] = $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_m . '-' . $end_d . ' ' . $end_Hi;
                    }
                }else{//不同年
                    if($start_m == $end_m && $start_d == $end_d){//不跨天
                        $v['activity_start_time'] = $start_Y . '-' . $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_m . '-' . $end_d . ' ' . $end_Hi;
                    }else{//跨天
                        $v['activity_start_time'] = $start_Y . '-' . $start_m . '-' . $start_d . ' ' . $start_Hi;
                        $v['activity_end_time'] = $end_Y . '-' . $end_m . '-' . $end_d . ' ' . $end_Hi;
                    }
                }
            }
        }
        $this->apiSuccess ($data);
    }
    
    /**
     * 删除我收藏的资讯、活动
     * type：删除的类型  1 资讯  2 活动
     * ids：需要删除的记录   如1,2,3的形式
     */
    public function delCollect(){
        $parms = input('param.');
        $ids = explode(',', $parms['ids']);
        if($parms['type'] == 1){//删除资讯
            $res = Db::table('up_my_collection')
                ->where('collection_id', 'in', $ids)
                ->delete();
        }else{//删除活动
            $res = Db::table('up_my_activities')
                ->where('id', 'IN', $ids)
                ->delete();
        }
        if($res){
            return $this->apiSuccess();
        }else{
           return $this->apiError('E001');
        }
    }

    /**
     * 志愿者认证
     * name 姓名
     * card 身份证号
     * mechanism_id 机构id
     * shi 市id
     * hospital 医院id
     * department 科室id
     * title 职称
     * duty 职务
     * business 证件照
     */
    public function approve(){
        extract(input());
        if($name =="" || $card == ""
            ||$mechanism_id == "" ||$shi == ""
            || $hospital == "" ||$department == ""
            ||$title == "" || $duty == ""||
            $business == ""){
            $this->apiError (110);
        }
        
        $param = [
            'user_rel_name'=>$name,
            'user_card'=>$card,
            'user_to_mechanism_id'=>$mechanism_id,
            'user_shi'=>$shi,
            'user_hospital'=>$hospital,
            'user_department'=>$department,
            'user_title'=>$title,
            'user_post'=>$duty,
            'user_business_image'=>$business,
            'user_attestation'=>2,
            'user_join_time' => date('Y-m-d H:i:s'),//提交资料时间
        ];
        $res = Db::table('up_u_user')->where('user_id',$user_id)->update($param);
        if($res){
            $list = [];
            $uid = (string)$user_id;
            array_push($list, $uid);
            $msg = '您的志愿者申请已经提交成功，工作人员正在审核认证信息，请耐心等待。';
            try{
                $this->Jpush(1, $list, '您的审核提交成功！', ['type'=>1], $msg, 3);
            }catch(\Exception $e){
                
            }
            $this->apiSuccess ('提交成功');
        }else{
            $this->apiError ('K100');
        }
    }

    /**
     * 获取机构 & 搜索机构
     */
    public function getMechanism(){
        extract(input());
        $map['mechanism_status'] = 2;
        $map['mechanism_id'] = ['neq', 1];
        if($key != ""){
            $map['mechanism_name'] =  ['like',"%" . $key . "%"];
        }
        $data = Db::table('up_mechanism')
            ->where($map)
            ->field('mechanism_id,mechanism_code,mechanism_name as name,mechanism_logo')
            ->select();
        $this->apiSuccess ($data);
    }

    /**
     * 获取医院 科室、职务、职称数据 & 搜索
     */
    public function getHospital(){
        extract(input());
        $map['assortment_type'] = $type;
        if($key != ""){
            $map['assortment_name'] =  ['like',"%" . $key . "%"];
        }
        $data = Db::table('up_assortment')
            ->where($map)
            ->field('assortment_id,assortment_name as name')
            ->select();
        $this->apiSuccess ($data);
    }
    
    /**
     * 认证审核成功/失败原因
     * user_id:用户ID
     */
    public function falseReason(){
        $params = input('param.');
        $user_id = $params['user_id'];
        $false_reason = Db::table('up_u_user')
            ->field('user_false_reason')
            ->where('user_id', $user_id)
            ->find();
        return $this->apiSuccess($false_reason);
    }
    
    /**
     * 我的订单列表
     * page：当前页码
     */
    public function myOrderList(){
        $params = input('param.');
        $where = [
            'o.user_id' => $params['user_id'],//本用户
            'o.order_status' => 1,//已完成
        ];
        $field = 'uc.classroom_img, uc.classroom_title, o.pay_time, o.order_id, o.order_status';
        $classroomOrderModel = new ClassroomOrderModel();
        $lists = $classroomOrderModel->myOrderList($where, '', $field, $params['page']);
        foreach($lists as &$list){
            $list['pay_time'] = substr($list['pay_time'], 0, 10);
        }
        return $this->apiSuccess($lists);
    }
    
    /**
     * 订单详情
     * order_id：订单ID
     */
    public function orderInfo(){
        $params = input('param.');
        $where['o.order_id'] = $params['order_id'];
        $field = 'o.order_id, o.order_money, o.order_type, o.order_number, o.order_time, o.pay_time,
        uc.classroom_img, uc.classroom_title';
        $classroomOrderModel = new ClassroomOrderModel();
        $orderInfo = $classroomOrderModel->myOrderList($where, $params['order_id'], $field, '');
        return $this->apiSuccess($orderInfo);
    }
    
    /**
     * 删除订单
     * order_id：订单ID
     */
    public function delOrder(){
        $params = input('param.');
        $classroomOrderModel = new ClassroomOrderModel();
        $res = $classroomOrderModel->delOrder($params['order_id']);
        if($res){
            return $this->apiSuccess();
        }else{
            return $this->apiError('E001');
        }
    }
    
    /**
     * 捐赠列表
     * page：当前页码
     */
    public function donateList(){
        $params = input('param.');
        $activityOrderModel = new ActivityOrderModel();
        $where = [
            'user_id' => $params['user_id'],//本用户
            'donate_status' => 1,//已完成
        ];
        $field = 'donate_id, pay_time, cate';
        $lists = $activityOrderModel->donateList($where, '', $field, $params['page']);
        foreach($lists as &$list){
            $list['pay_time'] = substr($list['pay_time'], 0, -3);
        }
        return $this->apiSuccess($lists);
    }
    
    /**
     * 订单详情
     * donate_id：捐赠记录ID
     */
    public function donateInfo(){
        $params = input('param.');
        $where['d.donate_id'] = $params['donate_id'];
        $field = 'd.donate_id, d.donate_money, d.pay_time, d.donate_type, d.donate_number, uia.activity_name';
        $activityOrderModel = new ActivityOrderModel();
        $donateInfo = $activityOrderModel->donateList($where, $params['donate_id'], $field, '');
        return $this->apiSuccess($donateInfo);
    }
    
    /**
     * 意见反馈
     * content：反馈内容
     */
    public function createFeedback(){
        $params = input('param.');
        $content = trim($params['content'], ' ');
        if(empty($content)){
            return $this->apiError(4006);
        }
        $num = mb_strlen($content, 'utf8');
        if($num > 200){
            return $this->apiError(4008);
        }
        $data = [
            'user_id' => $params['user_id'],//用户ID
            'feedback_content' => $content,//反馈内容
            'feedback_time' => date('Y-m-d H:i:s'),//反馈时间
        ];
        $feedbackModel = new FeedbackModel();
        $res = $feedbackModel->createFeedback($data);
        if($res){
            return $this->apiSuccess();
        }else{
            return $this->apiError('E000');
        }
    }
    
    /**
     * 关于我们
     */
    public function aboutUs(){
        $aboutUsModel = new AboutUsModel();
        $field = 'about_us';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }
    
    /**
     * 打赏捐款好处
     */
    public function donateBenefit(){
        $aboutUsModel = new AboutUsModel();
        $field = 'donate_benefit';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }
    
    /**
     * 用户协议
     */
    public function userArgement(){
        $aboutUsModel = new AboutUsModel();
        $field = 'user_argement';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }
    
    /**
     * 收费功能开关
     */
    public function ifPrice(){
        $aboutUsModel = new AboutUsModel();
        $field = 'price_button';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }
    
    /**
     * 获取省市数组
     */
    public function getArea(){
        $shengLists = Db::name('area')->field('district_id, district')->where('level', 1)->select();
        $shiLists = Db::name('area')->field('district_id, district, pid')->where('level', 2)->select();
        foreach($shengLists as $key => $shengList){
            for($i = 0; $i < count($shiLists); $i++){
                if($shiLists[$i]['pid'] == $shengList['district_id']){
                    $shengLists[$key]['shi'][] = $shiLists[$i];
                }
            }
        }
        return $this->apiSuccess($shengLists);
    }
    
    /**
     * 获取热门城市
     */
    public function getHotArea(){
        //热门城市ID
        $hotArea = [
            1002,
            1020,
            1832,
            1834,
            2965,
            1038,
            1182,
            1730,
            1178,
            1848,
            1288,
            1179,
            1731,
            2326,
            2810
        ];
        $hotArea = Db::table('up_area')
            ->field('district_id, district')
            ->where('district_id', 'IN', $hotArea)
            ->select();
        return $this->apiSuccess($hotArea);
    }
}